<?php
namespace backend\models;

use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;


class SignupForm extends ActiveRecord
{
    public $username;
    public $password;
    public $email;
    public $password_reset;
    //保存验证码
    public $verifyCode;
    //保存角色
    public $userRoles;


    public function rules()
    {
        return [
            [['username','password','verifyCode','email'],'required'],
            [['username', 'email','password_reset'], 'string', 'length' => [1,50]],
            [['email'],'email'],
            [['email','username'],'unique'],
            [['password_reset'],'safe'],
            [['verifyCode'],'captcha','captchaAction'=>'manager/captcha'],
            [['userRoles'],'safe'],
        ];
    }

    /**
     * @return array
     */
    public  function attributeLabels()
    {
        return [
            'username'=>'用户名',
            'password'=>'密码',
            'email'=>'邮箱',
            'password_reset'=>'密码重置令牌(可选)',
            'verifyCode'=>'验证码',
            'userRoles'=>'用户角色',
        ];
    }


    /**
     * 返回所有的角色
     * @return array
     */
    public static function getRoles()
    {
        $auth = \Yii::$app->authManager;
        $roles = ArrayHelper::getColumn($auth->getRoles(),'description');
        //VarDumper::dump($roles,10,true) ;
        return $roles;
    }


    /**
     *   注册用户
     * @return Admin|bool|null  admin注册用户的对象
     */
    public function signup(){
        if(!$this->validate()){
            return false;
        }

//        VarDumper::dump($this,10,true);exit;
        $adminMode = new Admin();

        $adminMode->username = $this->username;
        $adminMode->email = $this->email;
        //生成hash密码
        $adminMode->setPassword($this->password);
        //生成认证令牌
        $adminMode->generateAuthKey();
        //获取当前用户的登录ip
        $adminMode->last_login_ip = \Yii::$app->request->getUserIP();
        //设置最后的登录时间 更新时间
        $adminMode->last_login_time = time();
        $adminMode->updated_at = $adminMode->last_login_time;
        if(!empty($this->password_reset)){
            $adminMode->setPasswordResetToken($this->password_reset);
        }

        //随机生成加密字符串的盐
        $str = str_shuffle("abckefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+");
        $adminMode->salt = substr($str,0,5);

        //保存数据 返回结果
        //return $adminMode->save()?$adminMode:null;
        if($r = $adminMode->save()){
            //登录成功后给用户分配默认角色
            $auth = \Yii::$app->authManager;
            foreach($this->userRoles as $role){
                //关联用户和角色
                $auth->assign($auth->getRole($role),$adminMode->id);
            }
        }
        return $r?$adminMode:null;
    }


}